package jpa.entity.realm;

import jpa.entity.Account;
import jpa.repository.AccountRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by barton on 16-2-3.
 */
public class TokenRealm extends AuthorizingRealm {

    @Autowired
    private AccountRepository accountRepository;

    private Account account;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 获取认证信息
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws
            AuthenticationException {
        String userName = (String) token.getPrincipal();
        String password = String.valueOf((char[]) token.getCredentials());

        Account account = accountRepository.findByUsername(userName);

        this.account = account;

        if (null == account) {
            throw new UnknownAccountException("用户不存在");
        }

        if (null == password || !password.equals(account.getPassword())) {
            throw new IncorrectCredentialsException("密码错误"); //如果密码错误
        }

        //如果身份认证验证成功，返回一个AuthenticationInfo实现；
        return new SimpleAuthenticationInfo(userName, password, getName());
    }

}
